package cn.gailvlun.gll.presentation.xroom

import android.arch.lifecycle.ViewModelProviders
import android.databinding.DataBindingUtil
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.gailvlun.gll.R
import cn.gailvlun.gll.chatlib.event.CrossStatus
import cn.gailvlun.gll.chatlib.event.CrossStatusEvent
import cn.gailvlun.gll.databinding.FragmentCrossRoomMatchSuccessBinding
import cn.gailvlun.gll.presentation.base.BaseFragment
import cn.gailvlun.gll.presentation.xroom.vm.CrossRoomGameInfoViewModel
import cn.gailvlun.gll.util.LogUtil
import cn.gailvlun.gll.util.ProfileUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class CrossRoomMatchSuccessFragment : BaseFragment() {

    private lateinit var mBinding: FragmentCrossRoomMatchSuccessBinding

    override fun initComponent(inflater: LayoutInflater, container: ViewGroup?): View {
        EventBus.getDefault().register(this)

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_cross_room_match_success, container, false)


        mViewModel = ViewModelProviders.of(activity).get(CrossRoomGameInfoViewModel::class.java)

        return mBinding.root
    }

    private var mViewModel: CrossRoomGameInfoViewModel? = null

    override fun createHandler() {

    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        Glide.with(mContext)
                .load(R.drawable.img_cross_room_introduce)
                .into(object : SimpleTarget<Drawable>() {
                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                        mBinding.llBg.setBackgroundDrawable(resource)
                    }
                })

        Glide.with(mContext)
                .load(ProfileUtil.getProfile().avatar)
                .into(mBinding.rivMyHeader)

        Glide.with(mContext)
                .load(mViewModel?.getOppositeProfile()?.avatar)
                .into(mBinding.rivMatchHeader)
    }

    override fun loadData(savedInstanceState: Bundle?) {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onStartEvent(event: CrossStatusEvent) {
        if (event.status == CrossStatus.BEFORE_OPEN) {
            LogUtil.d("收到 BEFORE_OPEN")
            CrossRoomChatActivity.openActivity(mContext, event.oppositeId, event.gameId)
            activity.finish()
        }
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)

        super.onDestroy()
    }
}